// utils/toast.js
const DEFAULT_DURATION = 2000

class Toast {
  static config = {
    defaultIcon: 'none',
    defaultDuration: DEFAULT_DURATION,
    defaultMask: false,
    successIcon: 'success',
    errorIcon: 'error',
    loadingIcon: 'loading'
  }

  /**
   * 初始化配置
   * @param {object} config 配置项
   */
  static init(config = {}) {
    this.config = { ...this.config, ...config }
  }

  /**
   * 显示Toast
   * @param {object} options 配置项
   */
  static show(options = {}) {
    const {
      title = '',
      icon = this.config.defaultIcon,
      duration = this.config.defaultDuration,
      mask = this.config.defaultMask,
      image,
      position = 'center'
    } = options

    // 微信基础库2.10.0开始支持position参数
    const params = { title, icon, duration, mask }
    if (image) {
      params.image = image
      delete params.icon
    }
    if (wx.canIUse('showToast.object.position')) {
      params.position = position
    }

    wx.showToast(params)
  }

  // 成功提示
  static success(title, options = {}) {
    this.show({
      title,
      icon: this.config.successIcon,
      ...options
    })
  }

  // 错误提示
  static showError(title, options = {}) {
    this.show({
      title,
      icon: this.config.errorIcon,
      ...options
    })
  }

  // 加载中提示
  static loading(title = '加载中...', options = {}) {
    this.show({
      title,
      icon: this.config.loadingIcon,
      duration: 60000, // 长时间显示
      mask: true,
      ...options
    })
  }

  // 自定义图片提示
  static custom(title, image, options = {}) {
    this.show({
      title,
      image,
      ...options
    })
  }

  // 隐藏Toast
  static hide() {
    wx.hideToast()
  }

  // 快捷方法 - 顶部显示
  static top(title, options = {}) {
    if (wx.canIUse('showToast.object.position')) {
      this.show({
        title,
        position: 'top',
        ...options
      })
    } else {
      this.show({ title, ...options })
    }
  }

  // 快捷方法 - 底部显示
  static bottom(title, options = {}) {
    if (wx.canIUse('showToast.object.position')) {
      this.show({
        title,
        position: 'bottom',
        ...options
      })
    } else {
      this.show({ title, ...options })
    }
  }
}

module.exports= Toast